package com.hdrx.fundhelper.config;


import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.context.annotation.Configuration;

import java.io.UnsupportedEncodingException;

/**
 * @author: houdx
 * @description:
 * @date: 2023/8/11 14:41
 */
@Configuration
public class RabbitConfig {


    /**
     * 所有的消息发送都会转换成JSON格式发到交换机
     *
     * @param connectionFactory
     * @return
     */
    public RabbitTemplate rabbitTemplate(final ConnectionFactory connectionFactory) {
        final RabbitTemplate rabbitTemplate = new RabbitTemplate(connectionFactory);
        rabbitTemplate.setMessageConverter(new Jackson2JsonMessageConverter());

        //消息是否必须路由到一个队列中，配合Return使用
        rabbitTemplate.setMandatory(true);

        // 消息返回, yml需要配置 publisher-returns: true
        // 为RabbitTemplate设置ReturnsCallback
        //主要是两个回调，一个是confirm回调，一个是return回调，这两个有什么不同呢？
        //经检验得知，如果推送去一个不存在交换机上，那么就会触发confirm回调；如果推送去一个存在的交换机，但对应的路由键（或者说队列）不存在，则会触发return回调。

        rabbitTemplate.setReturnsCallback(returned -> {
            String exchange = returned.getExchange();
            Message message = returned.getMessage();
            int replyCode = returned.getReplyCode();
            String replyText = returned.getReplyText();
            String routingKey = returned.getRoutingKey();

            System.out.println("--------收到无法路由回发的消息--------");
            System.out.println("ReturnCallback:     " + "消息：" + message);
            System.out.println("ReturnCallback:     " + "回应码：" + replyCode);
            System.out.println("ReturnCallback:     " + "回应信息：" + replyText);
            System.out.println("ReturnCallback:     " + "交换机：" + exchange);
            System.out.println("ReturnCallback:     " + "路由键：" + routingKey);
            System.out.println("properties:" + message.getMessageProperties());
            try {
                System.out.println("body:" + new String(message.getBody(), "UTF-8"));
            }catch (UnsupportedEncodingException e){
                e.getStackTrace();
            }
        });


        // Confirm异步确认，收到服务端的ACK以后会调用
        rabbitTemplate.setConfirmCallback(new RabbitTemplate.ConfirmCallback() {
            @Override
            public void confirm(CorrelationData correlationData, boolean ack, String cause) {
                System.out.println("--------收到服务端异步确认--------");
                System.out.println("ConfirmCallback:     " + "相关数据：" + correlationData);
                System.out.println("ConfirmCallback:     " + "确认情况：" + ack);
                System.out.println("ConfirmCallback:     " + "原因：" + cause);
            }
        });
        return rabbitTemplate;

    }
}
